<?php

namespace App\Traits;

use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * 短信相关 Trait
 *
 * @author: WangBin
 * @date: 2021/9/16
 */
trait SmsTrait
{
    /**
     * 生成短信验证码，并存入缓存 5分种
     *
     * @param string $scene
     * @param string $mobile
     * @return int
     * @throws BusinessException
     */
    public function createSmsCode(string $scene, string $mobile)
    {
        // 随机生成六位验证码
        $code = random_int(100000, 999999);
        // 1分钟只能获取一次验证码 当天只能获取10次
        $lock = Cache::add($scene . '_captcha_lock_' . $mobile, 1, 60);
        if(!$lock) {
            throw new BusinessException(ResponseCode::PHONE_CODE_BUSY);
        }
        $countKey = $scene . '_captcha_count_' . $mobile;
        if(Cache::has($countKey)) {
            $count = Cache::increment($countKey);
            if($count > 10) {
                throw new BusinessException(ResponseCode::PHONE_CODE_TIMES_10);
            }
        } else {
            Cache::put($countKey, 1, Carbon::tomorrow()->diffInSeconds(now()));
        }

        // 存入缓存 5 分钟有效
        Cache::put($scene . '_captcha_' . $mobile, $code, 5 * 60);
        return $code;
    }

    /**
     * 发送短信
     *
     * @param string $scene
     * @param string $content
     */
    public function sendSms(string $scene, string $content)
    {

    }

    /**
     * 校验验证码一致
     *
     * @param string $scene
     * @param string $mobile
     * @param string $smsCode
     * @return bool
     */
    public function verifySmsCode(string $scene, string $mobile, string $smsCode)
    {
        return Cache::get($scene . '_captcha_' . $mobile, '') == $smsCode;
    }

    /**
     * 清除验证码
     *
     * @param string $scene
     * @param string $mobile
     * @return bool
     */
    public function deleteSmsCode(string $scene, string $mobile)
    {
        return Cache::forget($scene . '_captcha_' . $mobile);
    }
}